<template>
  <div class="face-query">
    <h1>人脸查询</h1>

    <!-- 摄像头区域 -->
    <div v-if="isCameraOpen" class="camera-box">
      <video ref="video" autoplay></video>
      <button @click="capturePhoto">拍照</button>
      <button @click="toggleCamera">关闭摄像头</button>
    </div>

    <!-- 上传图片区域 -->
    <div v-else>
      <input type="file" accept="image/*" @change="handleFileUpload" />
      <button @click="toggleCamera">打开摄像头</button>
    </div>

    <!-- 显示拍摄或上传的图片 -->
    <div v-if="imageSrc" class="image-preview">
      <img :src="imageSrc" alt="预览图片" />
      <button @click="submitImage">提交查询</button>
    </div>

    <!-- 查询结果 -->
    <div v-if="result" class="result">
      <h2>查询结果</h2>
      <p>{{ result.msg }}</p>
      <pre>{{ result.data }}</pre>
    </div>
  </div>
</template>

<script>
import { queryFace } from "@/api/face/face"; // 导入封装好的接口

export default {
  data() {
    return {
      imageUrl: "",
      isCameraOpen: false, // 是否开启摄像头
      imageSrc: null, // 拍摄或上传的图片
      result: null, // 查询结果
      mediaStream: null, // 摄像头流
    };
  },
  methods: {
    check() {
      console.log(this.imageUrl);
    },
    // 打开/关闭摄像头
    async toggleCamera() {
      if (this.isCameraOpen) {
        // 关闭摄像头
        this.stopCamera();
        this.isCameraOpen = false;
      } else {
        // 打开摄像头
        this.isCameraOpen = true;
        await this.$nextTick(); // 等待 DOM 更新

        try {
          // 请求摄像头权限
          this.mediaStream = await navigator.mediaDevices.getUserMedia({
            video: true,
          });

          // 确保 this.$refs.video 存在
          if (this.$refs.video) {
            // 将摄像头流绑定到 <video> 元素
            this.$refs.video.srcObject = this.mediaStream;
          } else {
            console.error("未找到 video 元素");
          }
        } catch (error) {
          // 处理错误
          console.error("摄像头访问失败:", error);

          // 根据错误类型提示用户
          if (error.name === "NotAllowedError") {
            alert("请允许访问摄像头权限。");
          } else if (error.name === "NotFoundError") {
            alert("未找到摄像头设备，请确保摄像头已连接。");
          } else {
            alert("无法访问摄像头，请重试。");
          }
        }
      }
    },

    // 关闭摄像头
    stopCamera() {
      if (this.mediaStream) {
        this.mediaStream.getTracks().forEach((track) => track.stop());
        this.mediaStream = null;
      }
    },

    // 拍照
    capturePhoto() {
      const video = this.$refs.video;
      const canvas = document.createElement("canvas");
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const context = canvas.getContext("2d");
      context.drawImage(video, 0, 0, canvas.width, canvas.height);

      // 将图片转换为 Data URL
      this.imageSrc = canvas.toDataURL("image/jpeg");
    },

    // 处理文件上传
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.imageSrc = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    },

    // 提交图片到后端
    async submitImage() {
      if (!this.imageSrc) {
        alert("请先拍照或上传图片");
        return;
      }

      try {
        // 将 Data URL 转换为 Blob
        const blob = await fetch(this.imageSrc).then((res) => res.blob());
        const formData = new FormData();
        formData.append("image", blob, "photo.jpg");
        queryFace(formData).then((response) => {
          console.log(response);
          if (response.code == 200) {
            this.$message({
              message: response.msg,
              type: "success",
            });
            this.result = response;
          } else {
            this.$message.error(response.msg || "查询失败");
          }
        });
      } catch (error) {
        console.log("catch error");
        console.error("提交图片失败:", error);
        this.$message.error("提交图片失败，请重试");
      }
    },
  },
  beforeDestroy() {
    // 组件销毁时关闭摄像头
    this.stopCamera();
  },
};
</script>

<style scoped>
.face-query {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
}

.camera-box video {
  width: 100%;
  max-width: 400px;
  border: 1px solid #ccc;
}

.image-preview img {
  width: 100%;
  max-width: 400px;
  margin-top: 20px;
}

button {
  margin: 10px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

.result {
  margin-top: 20px;
  text-align: left;
}

pre {
  background: #f4f4f4;
  padding: 10px;
  border-radius: 5px;
}
</style>
